<template>
  <div class="lottery-scroll">
    <transition name="fade">
      <div :key="currentText" class="text">{{ currentText }}</div>
    </transition>
    <button @click="startLottery" :disabled="isRunning">开始</button>
    <button @click="stopLottery" :disabled="!isRunning">结束</button>
  </div>
</template>

<script>
  export default {
    data() {
      return {
        texts: [
          "中国",
          "美国",
          "俄罗斯",
          "英国",
          "法国",
          "德国",
          "印度",
          "日本",
          "巴西",
          "加拿大",
          "澳大利亚",
          "意大利",
          "西班牙",
          "墨西哥",
          "印度尼西亚",
          "土耳其",
          "沙特阿拉伯",
          "南非",
          "韩国",
          "阿根廷",
        ],
        currentText: '中国',
      intervalId: null,
      isRunning: false,
      intervalDuration: 100, // 初始间隔时间
      slowDownIntervalId: null,
    };
  },
  methods: {
    startLottery() {
      if (!this.isRunning) {
        this.intervalDuration = 100; // 重置为初始间隔时间
        this.intervalId = setInterval(() => {
          const currentIndex = this.texts.indexOf(this.currentText);
          let newIndex = currentIndex;
          while (newIndex === currentIndex) {
            newIndex = Math.floor(Math.random() * this.texts.length);
          }
          this.currentText = this.texts[newIndex];
        }, this.intervalDuration); // 使用数据属性作为时间间隔
        this.isRunning = true;
      }
    },
    stopLottery() {
      if (this.isRunning) {
        const slowDownDuration = 1000; // 总减速时间
        const steps = 10; // 减速步骤
        let currentStep = 0; // 当前减速步骤

        clearInterval(this.slowDownIntervalId); // 清除之前的减速定时器
        this.slowDownIntervalId = setInterval(() => {
          currentStep++;
          this.intervalDuration += slowDownDuration / steps; // 增加时间间隔以减速
          if (currentStep >= steps) {
            clearInterval(this.intervalId);
            clearInterval(this.slowDownIntervalId);
            this.intervalId = null;
            this.slowDownIntervalId = null;
            this.isRunning = false;
          }
        }, slowDownDuration / steps); // 每步的时间
      }
    }
  },
  beforeDestroy() {
    if (this.intervalId) {
      clearInterval(this.intervalId);
    }
    if (this.slowDownIntervalId) {
      clearInterval(this.slowDownIntervalId);
    }
  }
};
</script>

<style>
  .fade-enter-active,
  .fade-leave-active {
    transition: opacity 0.5s;
  }
  .fade-enter,
  .fade-leave-to {
    opacity: 0;
  }
  .lottery-scroll {
    height: 450px;
    overflow: hidden;
    position: relative;
  }
  .text {
    position: absolute;
    width: 100%;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    font-size: 124px;
    font-weight: bold;
  }
</style>
